<?php

namespace app\admin\controller;

use MongoDB\Driver\Exception\WriteConcernException;
use think\Db;
use think\Exception;

class Add
{
    //mongo对象
    public $mongo_obj;

    public function __construct()
    {
        try {
            $this->mongo_obj = Db::connect("db_mongo");
        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }

    //添加首页导航到mongo
    public function addHomeNavigation()
    {
        try {

            $mongo_obj = $this->mongo_obj->name('item_navigation');

            $addData = [];

            $navigation_name = '北京';

            //判断当前导航是不是已经存在

            $result = $mongo_obj->where(['navigation_name'=>$navigation_name])->find();
            if($result){
                throw new Exception('当前导航已经被添加',1);
            }

            //导航名
            $addData['navigation_name'] = $navigation_name;

            //导航显示状态
            $addData['navigation_status'] = 1;

            //导航的权重
            $addData['navigation_weight'] = 99;

            $addData['scene_id'] = 'a101';

            $result = $mongo_obj->insertGetId($addData);

            if($result){
                //返回给前端的数据
                $successBack = [];
                $successBack['msg'] = "添加导航[$navigation_name]成功";
                successBack($successBack);
            }else{
                throw new Exception("添加导航[$navigation_name]失败",1);
            }
        }catch (\Exception $exception){
            errorBack($exception);
        }
    }
}